package com.complex.spring.mvc.controller;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.complex.spring.mvc.dal.UserDO;
import com.complex.spring.mvc.service.LoginService;

/***
 * 注意requestMapping中的路径 以/开头
 * 
 * @author gao
 * 
 */
@Controller
@RequestMapping("/user.controller")
@SessionAttributes("C")
public class UserController {

	private static final Log logger = LogFactory.getLog(UserController.class);

	@Autowired
	LoginService loginService;

	/**
	 *取得user 使用get方式提交,参数中包括getUser,即 user.controller?getUser=xxxx&loginId=xxxx
	 * 若改成 @RequestMapping(params="getUser=abc", method={RequestMethod.GET})
	 * 则必须使用 user.controller?getUser=abc&loginId=xxxx
	 * 
	 * @param loginId
	 * @param model
	 * @return ModelAndView
	 */
	@RequestMapping(params = "getUser", method = { RequestMethod.GET })
	public ModelAndView getUser(String loginId, ModelMap model, UserDO user1,
			@RequestParam(value = "loginId", required = false) String id,
			@ModelAttribute("B") String b) {
		// 输出log信息
		if (logger.isInfoEnabled()) {
			logger
					.info("=======================LoginAnnoController handleRequest=======================");
		}

		if (StringUtils.isEmpty(loginId)) {
			logger
					.error("=======================LoginAnnoController loginId is empty=======================");
			// return new ModelAndView("jsp/error.jsp");
		}

		// 处理业务逻辑
		UserDO user = loginService.getUser();
		model.addAttribute("user", user);
		// 原先B中的值是A(getA方法中存入) 这里通过@ModelAttribute("B")取得了b
		System.out.println(b);
		
		//类声明中指明"C"属性为被存入session
		model.addAttribute("C", "C");
		// 返回到login.jsp
		return new ModelAndView("jsp/user.jsp");

	}

	@ModelAttribute("B")
	public String getA() {
		return "A";
	}
	
	/**
	 * 该类声明中使用@SessionAttributes("C"),指明"C"属性会被存入session
	 * http://localhost:8080/user.controller?getUserAgain=abc   来再次访问是,可以看到c是有值的
	 * @param c
	 * @param status
	 * @return
	 */
	@RequestMapping(params = "getUserAgain", method = { RequestMethod.GET })
	public ModelAndView getUserAgain(@ModelAttribute("C") String c,SessionStatus status) {
		System.out.println(c);
		status.setComplete();		
		return new ModelAndView("jsp/user.jsp");
	}
}
